﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using NHibernate.Properties;
using NHibernate.Engine;

namespace cludg.Repository.NHibernate.Utils
{
	public class DictionaryPropertyAccessor : IPropertyAccessor
	{
		public bool CanAccessThroughReflectionOptimizer
		{
			get { return true; }
		}

		public IGetter GetGetter(Type theClass, string propertyName)
		{
			return new GetterSetter(propertyName);
		}

		public ISetter GetSetter(Type theClass, string propertyName)
		{
			return new GetterSetter(propertyName);
		}

		protected class GetterSetter : IGetter, ISetter
		{
			protected readonly string _propertyName;

			public GetterSetter(string propertyName)
			{
				_propertyName = propertyName;
			}

			public object Get(object target)
			{
				Type targetType = target.GetType();
				var prop = targetType.GetProperty("Item");
				return prop.GetValue(target, new object[] { _propertyName });
			}

			public object GetForInsert(object owner, IDictionary mergeMap, ISessionImplementor session)
			{
				return Get(owner);
			}

			public MethodInfo Method
			{
				get { return null; }
			}

			public string PropertyName
			{
				get { return _propertyName; }
			}

			public Type ReturnType
			{
				get { return typeof(object); }
			}

			public void Set(object target, object value)
			{
				Type targetType = target.GetType();
				var prop = targetType.GetProperty("Item");
				prop.SetValue(target, value, new object[] { _propertyName });
			}
		}
	}
}
